# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: conftest.py
# Time: 16:32

import os

import allure
import pytest

from bin.config.base_driver import BaseDriver
from bin.utils.log_util import logger
from bin.utils.dingding_util import SendMessage
from bin.utils.file_util import FilePath

_driver = None


def pytest_addoption(parser):
    parser.addoption("--cmdopt", action="store", default="device_info", help=None)


@pytest.fixture(scope="session")
def cmdopt(pytestconfig):
    # 两种写法
    return pytestconfig.getoption("--cmdopt")


@pytest.fixture(scope="session")
def common_driver(log, cmdopt):
    global _driver
    _driver = BaseDriver(eval(cmdopt), log).driver()
    log.info("APPium启动参数：{}".format(cmdopt))
    driver = _driver
    yield driver


@pytest.fixture(scope="session")
def log():
    global log
    log = logger
    return log


# @pytest.hookimpl(tryfirst=True, hookwrapper=True)
# def pytest_runtest_makereport(item):
#     # 获取每个用例状态的钩子方法的调用结果
#     outcome = yield
#     rep = outcome.get_result()
#     # 仅仅获取用例call 执行结果是失败的情况, 不包含 setup/teardown
#     if rep.when == "call" and rep.failed:
#
#         mode = "a" if os.path.exists("failures") else "w"
#         with open("failures", mode) as f:
#             if "tmpdir" in item.fixturenames:
#                 extra = " (%s)" % item.funcargs["tmpdir"]
#             else:
#                 extra = ""
#             f.write(rep.nodeid + extra + "\n")
#         if hasattr(_driver, "get_screenshot_as_png"):
#             with allure.step("添加失败截图。。。"):
#                 allure.attach(_driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)

# 测试报告失败截图  allure失败截图
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    outcome = yield
    report = outcome.get_result()
    report.description = str(item.function.__doc__)

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            img_path = os.path.join(FilePath().get_output_information(),"img")
            img_name = _driver.save_screenshot(img_path+"/"+"用例失败截图.png")
            SendMessage().run_send("APPIUM自动化测试报告")
            with open(img_name, mode="rb") as f:
                file = f.read()
            allure.attach(file, "失败截图", allure.attachment_type.PNG)